#include "beameffectactor.h"
#include "effectcontainermanager.h"

namespace VrDataCore
{
	BeamEffectActor::BeamEffectActor():_beamActor(NULL)
	{}

	BeamEffectActor::~BeamEffectActor()
	{}

	void BeamEffectActor::apply(CoreBase::ActorBase* bindingactor)
	{
		if(!isIdle())
			return;
		if(!_beamActor.valid())
		{
			_beamActor = new BeamActor;
			_beamActor->init();
			_beamEffectCallback = new BeamEffectCallback(this);
		}
		osg::Vec3 actorpos = dynamic_cast<TransformableActor*>(bindingactor)->getTranslation();
		float s = _distanceWithBeam/(_destinationPosition-actorpos).length();
		if(s>1.0f)
			s = 1.0f;
		osg::Vec3 p = actorpos+(_destinationPosition-actorpos)*s;
		EffectContainerManager::GetInstance().addEffectNode(_beamActor->getDrawable()->getOSGNode());
		_beamActor->setTranslation(p);
		_beamActor->getDrawable()->getOSGNode()->addUpdateCallback(_beamEffectCallback);
		EffectBase::apply(bindingactor);
	}

	void BeamEffectActor::unApply(CoreBase::ActorBase* bindingactor)
	{
		if(isIdle())
			return;
		if(_beamActor.valid())
		{
			_beamActor->getDrawable()->getOSGNode()->removeUpdateCallback(_beamEffectCallback);
			EffectContainerManager::GetInstance().removeEffectNode(_beamActor->getDrawable()->getOSGNode());
		}
		EffectBase::unApply(bindingactor);
	}

	void BeamEffectActor::buildPropertyMap()
	{}

	void BeamEffectActor::setDestinationPosition(const osg::Vec3& pos)
	{
		_destinationPosition = pos;
	}

	void BeamEffectActor::setDistanceWithBeam(int dis)
	{
		_distanceWithBeam = dis;
	}

	void BeamEffectActor::update()
	{
		osg::Vec3 actorpos = dynamic_cast<TransformableActor*>(_bindingMeshDrawableActor)->getTranslation();
		float s = _distanceWithBeam/(_destinationPosition-actorpos).length();
		if(s>1.0f)
			s = 1.0f;
		osg::Vec3 p = actorpos+(_destinationPosition-actorpos)*s;
		p.z() = -15;
		_beamActor->setTranslation(p);
	}
}